/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bibliOnline.db;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContextEvent;

/**
 *  Recupera tutti i dettagli della connessione a db2
 *  dal file di proprieta' /WEB-INF/db2.properties
 *  e instaura una connessione che
 *  ha lo stesso tempo di vita dell'applicazione
 * @author luca
 */
public class DBConnection {

    private static String URL;
    private static String USER;
    private static String PASSWORD;
    private static String DRIVER;
    private static Connection connection;
    private static Properties connectionProperties;

    public DBConnection(Properties properties) {
        connection = null;
        connectionProperties = properties;
    }

    public void init(ServletContextEvent event) {

        URL = connectionProperties.getProperty("db2.url");
        USER = connectionProperties.getProperty("db2.user");
        PASSWORD = connectionProperties.getProperty("db2.password");
        DRIVER = connectionProperties.getProperty("db2.driver");

        try {
            Class.forName(DRIVER);
            connection = DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (Exception ex) {
            Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
            return;
        }

        System.out.println("CONNECTION ESTABLISHED");
    }

    public void destroy(ServletContextEvent event) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException ex) {
                Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, null, ex);
                return;
            }
        }
        System.out.println("CONNECTION CLOSED");
    }

    public static PreparedStatement prepareStatement(String sql) throws Exception {
        if (connection == null) {
            throw new Exception("Connessione non stabilita");
        }

        PreparedStatement statement;
        statement = connection.prepareStatement(sql);

        return statement;
    }
    
    public static CallableStatement prepareCall(String sql) throws Exception {
        if (connection == null) {
            throw new Exception("Connessione non stabilita");
        }

        CallableStatement statement;
        statement = connection.prepareCall(sql);
        
        return statement;
    }

    public static String getProperty(String property_name) 
    {
        return connectionProperties.getProperty(property_name);
    }

}
